package com.squareshoot.picCheckin;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.provider.SearchRecentSuggestions;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	Preference emailPref,passwordPref;
	ProfileDb mDbHelper;
	private Context context;
	protected final int DIALOG_CLEAR = 111;
	protected final int DIALOG_LOGOUT = 222;
	private boolean isAuthent= false;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		setContentView(R.layout.prefs);
		context = getApplicationContext();

		PackageInfo pInfo = null;
		try{
			pInfo = getPackageManager().getPackageInfo(Common.PACKAGENAME,PackageManager.GET_META_DATA);
		} catch (NameNotFoundException e) {
			pInfo = null;
		}
		if(pInfo != null)
			findPreference("version").setSummary(pInfo.versionName+" build "+pInfo.versionCode);


		emailPref = findPreference("emailPref");
		passwordPref = findPreference("passwordPref");
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		isAuthent=prefs.getBoolean("isAuthent",false);
		if(isAuthent)
			emailPref.setEnabled(false);
			



		mDbHelper = new ProfileDb(this);
		mDbHelper.open();
		Cursor c = mDbHelper.fetchProfile(1);
		int count = c.getCount();
		if(count>0){
			emailPref.setSummary(c.getString(c.getColumnIndexOrThrow(ProfileDb.KEY_EMAIL)));
		}else{ //Rien dans la base, on cree un profil sans rien
			mDbHelper.createProfile("","","",null);
		}
		mDbHelper.close();
		c.close();

		emailPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			public boolean onPreferenceChange(Preference preference, Object newValue) {

				mDbHelper.open();
				mDbHelper.dropProfileTable();
				if(Common.HIGHDEBUG)
					Log.i(Common.TAG,"Pref base crÃ©e");
				mDbHelper.createProfile("","","",null);
				if (mDbHelper.updateEmail(1,(String)newValue))
					emailPref.setSummary((String)newValue);
				mDbHelper.close();
				return true;

			}
		});

		passwordPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				mDbHelper.open();
				mDbHelper.updatePassword(1,(String)newValue);
				mDbHelper.close();
				passwordPref.setSummary("");
				return true;
			}
		});

		findPreference("clearSearchHistory").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				showDialog(DIALOG_CLEAR);
				return true;
			}
		});

		findPreference("disco").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				showDialog(DIALOG_LOGOUT);
				return true;
			}
		});

		findPreference("update").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Common.MARKET_URL)));
				return false;
			}
		});

		findPreference("changelog").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				startActivity(new Intent(PrefsActivity.this, Changelog.class));
				return false;
			}
		});
		
		findPreference("sendlogcat").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				startActivity(new Intent(PrefsActivity.this, SendLogActivity.class));
				return false;
			}
		});
		
		findPreference("localisation").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));
				return false;
			}
		});
		
		findPreference("foursqsettings").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Common.FOURSQ_SETTINGS_URL)));
				return false;
			}
		});
		
		Button save = (Button)findViewById(R.id.savePrefs);
		save.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String login;
				String password;
				mDbHelper.open();
				Cursor c = mDbHelper.fetchProfile(1);
				mDbHelper.close();

				int count = c.getCount();
				if(count>0){
					login=c.getString(c.getColumnIndexOrThrow(ProfileDb.KEY_EMAIL));
					password=c.getString(c.getColumnIndexOrThrow(ProfileDb.KEY_PWD));
					if(login.equals("")){
						Toast erreurToast = Toast.makeText(PrefsActivity.this,R.string.verifyLogin,Toast.LENGTH_LONG);
						erreurToast.setGravity(Gravity.CENTER, 0, 0);
						erreurToast.show();
						if(Common.HIGHDEBUG)
							Log.e(Common.TAG,"Prefs : pas de login");
					}

					else if(password.equals("")){
						Toast erreurToast = Toast.makeText(PrefsActivity.this,R.string.verifyPassword,Toast.LENGTH_LONG);
						erreurToast.setGravity(Gravity.CENTER, 0, 0);
						erreurToast.show();
						if(Common.HIGHDEBUG)
							Log.e(Common.TAG,"Prefs : pas de password");
					}
					else{
						if(Common.HIGHDEBUG)
							Log.e(Common.TAG,"Prefs : on Quitte apres avoir sauve");
						finish();
					}
				}
				else{
					Toast erreurToast = Toast.makeText(PrefsActivity.this,R.string.verifyBoth,Toast.LENGTH_LONG);
					erreurToast.setGravity(Gravity.CENTER, 0, 0);
					erreurToast.show();
					if(Common.HIGHDEBUG)
						Log.e(Common.TAG,"Prefs : ni login ni password");
				}
				c.close();

			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		if(Common.HIGHDEBUG)
			Log.e(Common.TAG,"Prefs : on Destroy");
	}

	@Override
	protected void onPause() {
		super.onPause();  
		getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);    
	}


	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

	}


	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_CLEAR:
			AlertDialog.Builder builderClear = new AlertDialog.Builder(this);
			builderClear.setTitle(getString(R.string.clearHistory)+"?")
			.setCancelable(false)
			.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					SearchRecentSuggestions suggestions = new SearchRecentSuggestions(context,VenueSuggestionProvider.AUTHORITY,VenueSuggestionProvider.MODE);
					suggestions.clearHistory();
				}
			})
			.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alertClear = builderClear.create();
			return alertClear;
		case DIALOG_LOGOUT:
			AlertDialog.Builder builderLogout = new AlertDialog.Builder(this);
			builderLogout.setTitle(getString(R.string.logout)+"?")
			.setCancelable(false)
			.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					mDbHelper.open();
					//mDbHelper.updatePassword(1, "");
					//			        	   mDbHelper.updateCookie(1, "");
					mDbHelper.dropProfileTable();
					mDbHelper.close();

					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PrefsActivity.this);
					Editor editor = prefs.edit();
					editor.remove("emailPref");
					editor.remove("passwordPref");
					editor.putBoolean("isAuthent", false);
					editor.commit();

					emailPref.setEnabled(true);

					Bundle bundle = new Bundle();
					bundle.putString("from", "Prefs");
					Intent mIntent = new Intent();
					mIntent.putExtras(bundle);
					setResult(RESULT_OK, mIntent);
					finish();     	   
				}
			})
			.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alertLogout = builderLogout.create();
			return alertLogout;
		}
		return null;
	}
	@Override
	public boolean onKeyDown(int code,KeyEvent event){
		if(event.getKeyCode()==4){
//			Bundle bundle = new Bundle();
//			bundle.putString("from", "Prefs");
//			Intent mIntent = new Intent();
//			mIntent.putExtras(bundle);
//			setResult(RESULT_OK, mIntent);
			finish();     	   
			return true;
		}
		return false;
	}

}
